﻿<script lang="ts" setup name="productCard">
import { ref, reactive, onMounted } from "vue";
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from "element-plus";
import { downloadStreamFile } from "/@/utils/download";
import { useProductCardApi } from '/@/api/main/productCard';
import { useProductApi } from '/@/api/main/product';
import { useCustomerApi } from '/@/api/main/customer';
import editDialog from '/@/views/main/productCard/component/editDialog.vue'
import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import { formatDate } from '/@/utils/formatTime';
import ImportData from "/@/components/table/importData.vue";
import fillinDialog from '/@/views/main/productCard/component/fillinDialog.vue'
import transferDislog from '/@/views/main/productCard/component/transferDislog.vue'
import commonFunction from '/@/utils/commonFunction';

const { copyText } = commonFunction();
const productCardApi = useProductCardApi();
const printDialogRef = ref();
const editDialogRef = ref();
const importDataRef = ref();
const fillinDialogRef = ref();
const transferDislogRef = ref();
const state = reactive({
  exportLoading: false,
  tableLoading: false,
  queryLoading: false,
  stores: {},
  showAdvanceQueryUI: false,
  dropdownData: {} as any,
  selectData: [] as any[],
  tableQueryParams: {} as any,
  tableParams: {
    page: 1,
    pageSize: 20,
    total: 0,
    field: 'code', // 默认的排序字段
    order: 'descending', // 排序方向
    descStr: 'descending', // 降序排序的关键字符
  },
  tableData: [],
});

// 页面加载时
onMounted(async () => {
  state.queryLoading = true;
  var res = await useProductApi().getSelectList(null, false);
  state.dropdownData.productData = res.data.result;
  res = await useCustomerApi().getSelectList(null, false);
  state.dropdownData.customerData = res.data.result;
  state.queryLoading = false;
});

// 查询操作
const handleQuery = async (params: any = {}) => {
  state.tableLoading = true;
  state.tableParams = Object.assign(state.tableParams, params);
  const result = await productCardApi.page(Object.assign(state.tableQueryParams, state.tableParams)).then(res => res.data.result);
  state.tableParams.total = result?.total;
  state.tableData = result?.items ?? [];
  state.tableLoading = false;
};

// 列排序
const sortChange = async (column: any) => {
  state.tableParams.field = column.prop;
  state.tableParams.order = column.order;
  await handleQuery();
};

// 删除
const delProductCard = (row: any) => {
  ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await productCardApi.delete({ id: row.id });
    handleQuery();
    ElMessage.success("删除成功");
  }).catch(() => { });
};

// 复制链接
const copelinkProductCard = (row: any) => {
  if (row.status == 0) {
    ElMessage.warning("待生效的卡片不能复制链接");
    return;
  }
  ElMessageBox.confirm(`确定要复制并设置为已使用吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await productCardApi.copyLink({ id: row.id }).then(res => {
      copyText(res.data.result);
      handleQuery();
    });
  }).catch(() => { });
};

// 调拨库存弹窗
const transferProductCard = () => {
  state.selectData.filter(x => x.status == 2).length > 0 ? ElMessage.warning("已使用的卡不能调拨") : null;
  const codes = state.selectData.filter(x => x.status != 2).map(x => x.code).join('\n');
  transferDislogRef.value.openDialog({ codeRange: codes }, '调拨库存');
};

// 设置使用状态
const setStatusProductCard = (status: number) => {
  if (state.selectData.length == 0) {
    ElMessage.error("请至少选择一条记录");
    return;
  }
  ElMessageBox.confirm(`确定要设置为${status === 1 ? '未使用' : '已使用'}吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await productCardApi.setStatus({ idList: state.selectData.map(u => u.id), status }).then(res => {
      ElMessage.success("设置成功");
      handleQuery();
    });
  }).catch(() => { });
};

// 批量激活
const activateProductCard = () => {
  if (state.exportLoading) {
    return;
  }
  if (state.selectData.length == 0) {
    ElMessage.error("请至少选择一条记录");
    return;
  }

  if (state.selectData.filter(x => x.status == 0).length > 0) {
    ElMessage.error("待生效的卡不能激活");
    return;
  }

  if (state.selectData.filter(x => x.status == 2).length > 0) {
    ElMessage.error("已使用的卡不能激活");
    return;
  }

  ElMessageBox.prompt(`确定要批量激活吗?确认请输入选择的卡片数量:` + state.selectData.length, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async (val) => {
    if (val.value != state.selectData.length.toString()) {
      ElMessage.error("输入的数量不正确");
      return;
    }
    state.exportLoading = true;
    try {
      await productCardApi.activate({ idList: state.selectData.map(u => u.id), status: 2 }).then(res => {
        ElMessage.success(`激活成功${res.data.result.successCount}条，失败${res.data.result.failureCount}条`);
        state.exportLoading = false;
        handleQuery();
      });
    } finally {
      state.exportLoading = false;
    }
  }).catch(() => { });
};

// 批量删除
const batchDelProductCard = () => {
  ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await productCardApi.batchDelete(state.selectData.map(u => ({ id: u.id }))).then(res => {
      ElMessage.success(`成功批量删除${res.data.result}条记录`);
      handleQuery();
    });
  }).catch(() => { });
};

// 导出数据
const exportProductCardCommand = async (command: string) => {
  try {
    state.exportLoading = true;
    if (command === 'select') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map(u => u.id) });
      await productCardApi.exportData(params).then(res => downloadStreamFile(res));
    } else if (command === 'current') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams);
      await productCardApi.exportData(params).then(res => downloadStreamFile(res));
    } else if (command === 'all') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
      await productCardApi.exportData(params).then(res => downloadStreamFile(res));
    }
  } finally {
    state.exportLoading = false;
  }
}

handleQuery();
</script>
<template>
  <div class="productCard-container" v-loading="state.exportLoading">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
      <el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="ICCID">
              <el-input v-model="state.tableQueryParams.code" clearable placeholder="请输入ICCID" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="产品">
              <!-- <el-input v-model="state.tableQueryParams.productId" clearable placeholder="请输入产品Id"/> -->
              <el-select v-model="state.tableQueryParams.productId" placeholder="请选择产品" clearable>
                <el-option v-for="item in state.dropdownData.productData" :key="item.id" :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="状态">
              <g-sys-dict v-model="state.tableQueryParams.status" code="ProductCardStatusEnum" render-as="select"
                placeholder="请选择状态" clearable filterable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="批次号" v-auth="'productCard:noncustomerdata'">
              <el-input v-model="state.tableQueryParams.batchNumber" clearable placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="有效期" v-auth="'productCard:noncustomerdata'">
              <el-date-picker v-model="state.tableQueryParams.expirationDate" type="date" placeholder="有效期" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="所属客户" v-auth="'productCard:noncustomerdata'">
              <!-- <el-input v-model="state.tableQueryParams.customerId" clearable placeholder="请输入所属客户"/> -->
              <el-select v-model="state.tableQueryParams.customerId" placeholder="请选择客户" clearable>
                <el-option v-for="item in state.dropdownData.customerData" :key="item.id" :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item>
              <el-button-group style="display: flex; align-items: center;">
                <el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'productCard:page'"
                  v-reclick="1000"> 查询 </el-button>
                <el-button icon="ele-Refresh" @click="() => state.tableQueryParams = {}"> 重置 </el-button>
                <el-button icon="ele-ZoomIn" @click="() => state.showAdvanceQueryUI = true"
                  v-if="!state.showAdvanceQueryUI" style="margin-left:5px;"> 高级查询 </el-button>
                <el-button icon="ele-ZoomOut" @click="() => state.showAdvanceQueryUI = false"
                  v-if="state.showAdvanceQueryUI" style="margin-left:5px;"> 隐藏 </el-button>
                <el-button type="danger" style="margin-left:5px;" icon="ele-Delete" @click="batchDelProductCard"
                  :disabled="state.selectData.length == 0" v-auth="'productCard:batchDelete'"> 删除 </el-button>
                <el-button type="primary" style="margin-left:5px;" icon="ele-Plus"
                  @click="editDialogRef.openDialog(null, '新增实体卡')" v-auth="'productCard:add'"> 新增 </el-button>
                <el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportProductCardCommand">
                  <el-button type="primary" style="margin-left:5px;" icon="ele-FolderOpened" v-reclick="20000"
                    v-auth="'productCard:export'"> 导出 </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="select"
                        :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
                      <el-dropdown-item command="current">导出本页</el-dropdown-item>
                      <el-dropdown-item command="all">导出全部</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <!-- <el-button type="warning" style="margin-left:5px;" icon="ele-MostlyCloudy" @click="importDataRef.openDialog()" v-auth="'productCard:import'"> 导入 </el-button> -->
                <!-- <el-button type="warning" style="margin-left:5px;" icon="ele-FolderChecked"
                  @click="fillinDialogRef.openDialog('补充验证码')" v-auth="'productCard:fillin'"> 补充验证码 </el-button> -->
                <el-button type="warning" style="margin-left:5px;" icon="ele-Promotion" @click="transferProductCard()"
                  v-auth="'transferOrder:add'"> 调拨库存 </el-button>
                <!-- <el-button type="warning" style="margin-left:5px;" icon="ele-Check" @click="setStatusProductCard(2)"
                  v-auth="'productCard:setStatus'"> 设置为已使用
                </el-button>
                <el-button type="warning" style="margin-left:5px;" icon="ele-Close" @click="setStatusProductCard(1)"
                  v-auth="'productCard:setStatus'"> 设置为未使用
                </el-button>
                <el-button type="warning" style="margin-left:5px;" icon="ele-Key" @click="activateProductCard()"
                  v-auth="'productCard:activate'"> 批量激活
                </el-button> -->
              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="state.tableData" @selection-change="(val: any[]) => { state.selectData = val; }"
        style="width: 100%" v-loading="state.tableLoading" tooltip-effect="light" row-key="id" @sort-change="sortChange"
        border>
        <el-table-column type="selection" width="40" align="center"
          v-if="auth('productCard:batchDelete') || auth('productCard:export')" />
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop='productLabel' label='产品' show-overflow-tooltip />
        <el-table-column prop='batchNumber' label='批次号' width="180" show-overflow-tooltip
          v-auth="'productCard:noncustomerdata'" />
        <el-table-column prop='fullCode' label='ICCID' show-overflow-tooltip sortable />
        <el-table-column prop='code' label='ICCID' show-overflow-tooltip sortable
          v-auth="'productCard:noncustomerdata'" />
        <!-- <el-table-column prop='costPrice' label='成本价' width="120" show-overflow-tooltip
          v-auth="'productCard:noncustomerdata'" /> -->
        <el-table-column prop='expirationDate' label='有效期' width="120" v-auth="'productCard:noncustomerdata'"
          show-overflow-tooltip sortable>
          <template #default="scope">
            {{ formatDate(new Date(scope.row.expirationDate), 'YYYY-mm-dd') }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop='status' label='状态' width="100" show-overflow-tooltip sortable>
          <template #default="scope">
            <g-sys-dict v-model="scope.row.status" code="ProductCardStatusEnum" />
          </template>
        </el-table-column> -->
        <el-table-column prop='customerLabel' label='所属客户' show-overflow-tooltip
          v-auth="'productCard:noncustomerdata'" />
        <el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <ModifyRecord :data="scope.row" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right" show-overflow-tooltip
          v-if="auth('productCard:update') || auth('productCard:delete') || auth('productCard:copyLink')">
          <template #default="scope">
            <!-- <el-button icon="ele-CopyDocument" size="small" text type="primary" @click="copelinkProductCard(scope.row)"
              v-auth="'productCard:copyLink'"> 复制链接 </el-button> -->
            <el-button icon="ele-Delete" size="small" text type="primary" @click="delProductCard(scope.row)"
              v-auth="'productCard:delete'"> 修改 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:currentPage="state.tableParams.page" v-model:page-size="state.tableParams.pageSize"
        @size-change="(val: any) => handleQuery({ pageSize: val })"
        @current-change="(val: any) => handleQuery({ page: val })" layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100, 200, 500]" :total="state.tableParams.total" size="small" background />
      <ImportData ref="importDataRef" :import="productCardApi.importData" :download="productCardApi.downloadTemplate"
        v-auth="'supplier:import'" @refresh="handleQuery" />
      <printDialog ref="printDialogRef" :title="'打印实体卡'" @reloadTable="handleQuery" />
      <editDialog ref="editDialogRef" @reloadTable="handleQuery" />
      <fillinDialog ref="fillinDialogRef" @reloadTable="handleQuery" />
      <transferDislog ref="transferDislogRef" @reloadTable="handleQuery" />
    </el-card>
  </div>
</template>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
  width: 100%;
}
</style>